package com.voicenews.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.voicenews.R;
import com.voicenews.VoiceNewsApplication;
import com.voicenews.webserviceconnect.ICallbackHandler;
import com.voicenews.webserviceconnect.WebServiceConnector;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.text.style.UnderlineSpan;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

public class ArtilceShowActivity extends DashBoardActivity implements
		ICallbackHandler, OnCompletionListener, OnBufferingUpdateListener,
		OnPreparedListener, OnTouchListener, OnClickListener {
	private TextView textView;
	private final Handler handler = new Handler();
	private Button buttonRead;
	private SeekBar seekBarProgress;
	private TextView textStreamed;
	private ImageButton buttonPlayAndPause;
	private String articleId;
	private String titleArticle;
	private String urlArticle;
	private String urlAudioOfArticle;
	private String textArticle;
	private LinearLayout tagsLayout;
	private TextView fullPageLink;
	private MediaPlayer mediaPlayer;
	private int mediaFileLengthInMilliseconds; // this value contains the song
												// duration in milliseconds.
												// Look at getDuration() method
												// in MediaPlayer class

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("oncreate showarticle");
		setContentView(R.layout.view_extracted_article);
		setHeader(getIntent().getStringExtra("title"), true, true, false, true);
		textView = (TextView) findViewById(R.id.textView1);
		buttonRead = (Button) findViewById(R.id.button_stream);
		buttonPlayAndPause = (ImageButton) findViewById(R.id.button_play);
		tagsLayout = (LinearLayout) findViewById(R.id.tags);
		fullPageLink = (TextView) findViewById(R.id.full_page_label);

		titleArticle = getIntent().getStringExtra("title");
		urlArticle = getIntent().getStringExtra("urlString");
		articleId = getIntent().getStringExtra("articleId");
		urlAudioOfArticle = VoiceNewsApplication.hostAudio + articleId + ".mp3";

		fullPageLink.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						WebViewActivity.class);
				intent.putExtra("url", urlArticle);
				intent.putExtra("title", titleArticle);
				startActivity(intent);
			}
		});

		buttonPlayAndPause.setOnClickListener(this);

		textView.setMovementMethod(new ScrollingMovementMethod());

		buttonRead.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					System.out.println(urlAudioOfArticle);
					mediaPlayer.setDataSource(urlAudioOfArticle); // setup song
																	// from
					// http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
					// URL to mediaplayer data source
					mediaPlayer.prepareAsync(); // you must call this method
												// after
					// setup the datasource in
					// setDataSource method. After
					// calling prepare() the instance of
					// MediaPlayer starts load data from
					// URL to internal buffer.
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(e.getMessage());
				}
			}
		});

		seekBarProgress = (SeekBar) findViewById(R.id.seek_bar);
		seekBarProgress.setMax(99); // It means 100% .0-99
		seekBarProgress.setOnTouchListener(this);

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnBufferingUpdateListener(this);
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnPreparedListener(this);

		SharedPreferences setting = getSharedPreferences(
				VoiceNewsApplication.filePrefrences, MODE_PRIVATE);
		Map<String, String> params = new HashMap<String, String>();
		System.out.println(setting.getString("id", "noid"));
		params.put("url", urlArticle);
		params.put("id", setting.getString("id", "noid"));
		callWebService(params);
	}

	@Override
	public void response(String response) {
		System.out.println(response);
		System.out.println();
		try {
			JSONObject jso = new JSONObject(response);
			textArticle = jso.getString("text");
			textView.setText(textArticle);
			String[] tags;
			JSONArray jsonTags = jso.getJSONArray("tags");
			tags = new String[jsonTags.length()];
			for (int i = 0; i < jsonTags.length(); i++) {
				tags[i] = jsonTags.get(i).toString();
				System.out.println("tag : " + tags[i]);
			}

			View[] views = new View[tags.length];
			for (int i = 0; i < tags.length; i++) {
				final String text = tags[i];
				SpannableString content = new SpannableString(text);
				content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
				TextView textView = new TextView(getApplicationContext());
				textView.setText(content);
				textView.setTextColor(getResources().getColor(
						R.color.link_color));
				textView.setPadding(5, 0, 5, 0);
				views[i] = textView;
				textView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getApplicationContext(),
								SearchArticlesByTagActivity.class);
						intent.putExtra("tag", text);
						startActivity(intent);
					}
				});
			}

			populateText(tagsLayout, views, getApplicationContext());
			// mediaPlayer = new StreamingMediaPlayer(
			// extractedArticle.getSentences(), this);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// } catch (MalformedURLException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
		}

	}

	private void callWebService(Map<String, String> params) {
		WebServiceConnector webServiceConnector = new WebServiceConnector(VoiceNewsApplication.hostService
				+ "rest/services/", "extractedarticle", params, this,
				WebServiceConnector.GET_METHOD, this);
		webServiceConnector.execute();
	}

	private void populateText(LinearLayout ll, View[] views, Context mContext) {
		Display display = getWindowManager().getDefaultDisplay();
		ll.removeAllViews();
		@SuppressWarnings("deprecation")
		int maxWidth = display.getWidth() - 20;

		LinearLayout.LayoutParams params;
		LinearLayout newLL = new LinearLayout(mContext);
		newLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		newLL.setGravity(Gravity.LEFT);
		newLL.setOrientation(LinearLayout.HORIZONTAL);

		int widthSoFar = 0;

		for (int i = 0; i < views.length; i++) {
			LinearLayout LL = new LinearLayout(mContext);
			LL.setOrientation(LinearLayout.HORIZONTAL);
			LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
			LL.setLayoutParams(new ListView.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			// my old code
			// TV = new TextView(mContext);
			// TV.setText(textArray[i]);
			// TV.setTextSize(size); <<<< SET TEXT SIZE
			// TV.measure(0, 0);
			views[i].measure(0, 0);
			params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
					LayoutParams.WRAP_CONTENT);
			// params.setMargins(5, 0, 5, 0); // YOU CAN USE THIS
			// LL.addView(TV, params);
			LL.addView(views[i], params);
			LL.measure(0, 0);
			widthSoFar += views[i].getMeasuredWidth();// YOU MAY NEED TO ADD THE
														// MARGINS
			if (widthSoFar >= maxWidth) {
				ll.addView(newLL);

				newLL = new LinearLayout(mContext);
				newLL.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				newLL.setOrientation(LinearLayout.HORIZONTAL);
				newLL.setGravity(Gravity.LEFT);
				params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(),
						LL.getMeasuredHeight());
				newLL.addView(LL, params);
				widthSoFar = LL.getMeasuredWidth();
			} else {
				newLL.addView(LL);
			}
		}
		ll.addView(newLL);
	}

	@Override
	public void btnShareClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, urlArticle + "\n" + titleArticle);
		intent.putExtra(Intent.EXTRA_TITLE, titleArticle);
		intent.putExtra(android.content.Intent.EXTRA_SUBJECT, titleArticle);
		startActivity(Intent.createChooser(intent, "Share"));

	}

	/**
	 * Method which updates the SeekBar primary progress by current song playing
	 * position
	 */
	private void primarySeekBarProgressUpdater() {
		System.out.println(mediaPlayer.getCurrentPosition() + " : "
				+ mediaFileLengthInMilliseconds);
		int seek = (int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100);
		System.out.println("seek" + seek);
		seekBarProgress.setProgress(seek); // This math construction give a
											// percentage of
											// "was playing"/"song length"
		if (mediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
				public void run() {
					primarySeekBarProgressUpdater();
				}
			};
			handler.postDelayed(notification, 1000);
		}
	}

	@Override
	public void onClick(View v) {
		if (!mediaPlayer.isPlaying()) {
			mediaPlayer.start();
			buttonPlayAndPause.setImageResource(R.drawable.button_pause);
		} else {
			mediaPlayer.pause();
			buttonPlayAndPause.setImageResource(R.drawable.button_play);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v.getId() == R.id.seek_bar) {
			/**
			 * Seekbar onTouch event handler. Method which seeks MediaPlayer to
			 * seekBar primary progress position
			 */
			if (mediaPlayer.isPlaying()) {
				SeekBar sb = (SeekBar) v;
				int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
						* sb.getProgress();
				mediaPlayer.seekTo(playPositionInMillisecconds);
				primarySeekBarProgressUpdater();
			}
		}
		return false;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		/**
		 * Method which updates the SeekBar secondary progress by current song
		 * loading from URL position
		 */
		System.out.println(percent);
		seekBarProgress.setSecondaryProgress(percent);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		/**
		 * MediaPlayer onCompletion event handler. Method which calls then song
		 * playing is complete
		 */
		buttonPlayAndPause.setImageResource(R.drawable.button_play);
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		mediaPlayer.start();
		buttonPlayAndPause.setImageResource(R.drawable.button_pause);
		mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets
		// the
		// song
		// length
		// in
		// milliseconds
		// from
		// URL
		primarySeekBarProgressUpdater();
	}
}
